// sub_suzhou/enterpriseList/enterpriseList.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    searchParam: '',
    bankId: '',
    allocationIsshow: false,
    allselectCheckbox: false,
    originList: [],
    bankName: '',
    headType: 'visit_rate',
    total: '',
    pageNum: 1,
    pageSize: 8,
    fileName: '',
    serach_pro: '',
    selectCheckbox: [],
    checkBtachList: [],
    optype: '',
    range: '',
    showWin: false,
    showCheck: true,
    loadingIsshow: false,
    columns: ['测试选项1', '测试选项2', '测试选项3'],
    showORG: false,
    orgOptions: [],
    // 选中项目文字
    cascaderValue: '',
    // 选中选项对应的id
    cascaderId: '',
    fullPath: '',
    option: '',
    assignType: '',
    manages: [],
    showXZ: false,
    active: 'withdraw',
    agencyCode: '',
    haveDevice:''
  },
  cationClick() {
    this.setData({
      allocationIsshow: true
    })
  },
  assignment() {
   
    if (this.data.selectCheckbox.length == 0) {
      wx.showToast({
        icon: "none",
        title: "请选择企业",
      });
      return
    }
    let selectCheckbox = this.data.selectCheckbox;
    let originList = this.data.originList;
    let filter = originList.filter(item => selectCheckbox.includes(item.visitCorpId));
    // 如果filter 中 visitStatus 有一项不等于 未分配或者不等于 未分配至客户经理则不能分配
    let flag = filter.some(item => item.visitStatus != '未分配' && item.visitStatus != '未分配至客户经理' && item.visitStatus != '暂未分配');
    if (flag) {
      wx.showToast({
        icon: "none",
        title: "勾选企业中存在已走访数据",
        duration: 1500,
      });
      this.closeBtn();
      return
    }
    this.setData({
      showWin: true,
      columns: this.data.manages,
      showXZ: false,
      showORG: true
    })
  },
  allSelectChange(e) {

    this.data.allselectCheckbox = !this.data.allselectCheckbox
    this.setData({
      allselectCheckbox: this.data.allselectCheckbox
    })
    if (this.data.allselectCheckbox == false) {
      this.data.selectCheckbox = []
      this.setData({
        selectCheckbox: []
      })
     
    } else {
      let map = this.data.originList.map(item => item.visitCorpId);
      this.setData({
        selectCheckbox: map
      })
    }
  },
  onChange(e) {
    this.setData({
      cascaderValue: e.detail.value.text,
      cascaderId: e.detail.value.value,
      fullPath: e.detail.value.path
    });

  },
  onCancel() {

  },
  onConfirm(e) {

  },
  goback() {

    wx.navigateBack({
      delta: 1
    })
  },
  changeAssignType(e) {

    this.setData({
      assignType: e.detail,
    })
    if (e.detail == 'org') {
      // 添加确认弹窗
      wx.showModal({
        title: '提示',
        content: '确认分配吗？',
        success: (res) => {
          if (res.confirm) {

            this.setData({
              showWin: false
            })
            //TODO 添加确认分配接口
            // this.assign()
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })



      this.setData({
        // showXZ:true,
        // showORG:true
      })
      this.resetCascader();
    } else if (e.detail == 'person') {
      // this.resetCascader()
      this.setData({
        columns: this.data.manages,
        showXZ: false,
        showORG: true
      })

    }
  },

  getORG() {
    let params = {}
    params.token = wx.getStorageSync('token');
    params.userId = wx.getStorageSync("userInfo").userId
    getApp().globalData.request(
      '/corpVisit/getBankTree', params,
      "POST"
    ).then(res => {

   
      if (res.data.length > 0) {
        let list = res.data[0].children
        if (list.length > 0) {
          // 处理进度
          this.setData({
            orgOptions: res.data[0]
          })
          // 通过list给 columns 数组赋值
          let columns = []

          list.forEach(item => {
            let para = {}
            para.text = item.text
            para.value = item.value
            para.path = item.path
            columns.push(para)
          })
          this.setData({
            columns: columns
          })
        }
      }
    })
  },
  getManages() {
    let params = {}
    params.token = wx.getStorageSync('token');
    params.userId = wx.getStorageSync("userInfo").userId
    getApp().globalData.request(
      '/corpVisit/queryManageByAgencyCode', params,
      "POST"
    ).then(res => {
    
      if (res.data.length > 0) {
        let map = res.data.map(item => item.name);

        let manages = []

        res.data.forEach(item => {
          let itm = {}
          itm.text = item.name
          itm.value = item.userId
          manages.push(itm)
        })
        this.setData({
          manages: manages
        })
      }
    })
  },
  cancell() {
    this.setData({
      allocationIsshow: false
    })
  },
  showORG() {
    this.setData({
      showORG: true
    })
  },
  closeORG() {

    this.setData({
      showORG: false
    })
    // this.resetCascader()
  },
  //确定
  confirmORG(e) {
    let columns = this.data.columns
    this.setData({
      allocationIsshow: false
    })
    let cascaderValue = this.data.cascaderValue
    let cascaderId = this.data.cascaderId
    let fullPath = this.data.fullPath
    if (!cascaderValue) {
      cascaderValue = this.data.columns[0].text
      cascaderId = this.data.columns[0].value
      fullPath = this.data.columns[0].path
    } else {
      //选中的银行有值但有可能是上一次下钻的值，所以需要判断一下
      columns.filter(i => i.text == cascaderValue).length == 0 ? cascaderValue = columns[0].text : cascaderValue = cascaderValue
      columns.filter(i => i.value == cascaderId).length == 0 ? cascaderId = columns[0].value : cascaderId = cascaderId
      columns.filter(i => i.path == fullPath).length == 0 ? fullPath = columns[0].path : fullPath = fullPath
    }
    this.setData({
      cascaderValue: cascaderValue,
      cascaderId: cascaderId,
      fullPath: fullPath
    })
    let selectCheckbox = this.data.selectCheckbox;

    let params = {}
    params.token = wx.getStorageSync('token');
    params.userId = wx.getStorageSync("userInfo").userId
    // params.assignType = this.data.assignType; // 分配类型
    params.assignType = 'person'; // 分配类型
    params.assignId = this.data.cascaderId; // 银行id/人员id
    params.assignName = this.data.cascaderValue; //银行中文
    params.fullPath = fullPath; //银行全路径
    params.selectCheckbox = selectCheckbox; //操作类型

    let this_ = this;
    // 添加确认弹窗
    wx.showModal({
      title: '提示',
      content: '确认分配吗？',
      success: (res) => {
        if (res.confirm) {
          this_.setData({
            showWin: false
          })
          // 调用方法 /visit/corp_assign
          getApp().globalData.request(
            '/visit/corp_assign',
            params,
            "POST"
          ).then(res => {
           
            if (res.code == 200) {
              wx.showToast({
                title: '分配成功',
                icon: 'none',
              })
              this_.setData({
                cascaderValue: '',
                cascaderId: '',
                fullPath: '',
                selectCheckbox: '',
                assignType: '',
                showORG: false,
              })
              this_.firstSearch();
            }
          })
        } else if (res.cancel) {
          this_.setData({
            cascaderValue: '',
            cascaderId: '',
            fullPath: '',
            selectCheckbox: '',
            assignType: '',
            showORG: false,
            showWin: false,
          })
        
        }
      },
    })



  },
  //下钻
  drillDown(e) {
    // 下啦选项获取的值
    let columns = this.data.columns
    // 银行的层级元数据
    let orgOptions = this.data.orgOptions;
    // 当前选中银行的名称
    let cascaderValue = this.data.cascaderValue;
    if (!cascaderValue) {
      cascaderValue = this.data.columns[0].text
    } else {
      //选中的银行有值但有可能是上一次下钻的值，所以需要判断一下
      columns.filter(i => i.text == cascaderValue).length == 0 ? cascaderValue = columns[0].text : cascaderValue = cascaderValue
    }
    let drillNode = this.getLeafNodeByname(cascaderValue, orgOptions);
    if (drillNode && drillNode.children && drillNode.children.length > 0) {
      let drills = drillNode.children
      let columns = []
      drills.forEach(item => {
        let para = {}
        para.text = item.text
        para.value = item.value
        para.path = item.path
        columns.push(para)
      })
      this.setData({
        columns: columns
      })
    } else {
      wx.showToast({
        icon: "none",
        title: "无可下钻数据",
      });
    }
  },
  resetCascader() {

    // let list = this.data.orgOptions.children
    // // 通过list给 columns 数组赋值
    // let columns = []
    // list.forEach(item => {
    //   let para={}
    //   para.text=item.text
    //   para.value=item.value
    //   para.path=item.path
    //   columns.push(para)
    // })
    this.setData({
      columns: this.data.manages,
    })
  },

  serachProChange(e) {
    this.setData({
      serach_pro: e.detail,
    });
  },
  selectTab(e) {
    let title = e.detail.title;
    this.setData({
      active: e.detail.name,
    })
    // if (title == '分配') {
    // 分配前需要判断选中企业中是否有已分配的企业
    let selectCheckbox = this.data.selectCheckbox;
    let originList = this.data.originList;
    let filter = originList.filter(item => selectCheckbox.includes(item.visitCorpId));
    // 如果filter 中 visitStatus 有一项不等于 未分配或者不等于 未分配至客户经理则不能分配
    let flag = filter.some(item => item.visitStatus != '未分配' && item.visitStatus != '未分配至客户经理' && item.visitStatus != '未走访');
    if (flag) {
      wx.showToast({
        icon: "none",
        title: "勾选企业中存在已走访数据，请先取消勾选",
      });
      this.closeBtn();
      return
    }
    // } else {
    //
    // }

  },
  closeBtn() {
    this.setData({
      showWin: false,
      showCheck: false,
      assignType: '',
      selectCheckbox: [],
      checkBtachList: [],
    });
  },
  openBtn() {
    if (this.data.selectCheckbox.length == 0) {
      wx.showToast({
        icon: "none",
        title: "请选择企业",
      });
      return
    }

    let selectCheckbox = this.data.selectCheckbox;
    let originList = this.data.originList;
    let filter = originList.filter(item => selectCheckbox.includes(item.visitCorpId));
    // 如果filter 中 visitStatus 有一项不等于 未分配或者不等于 未分配至客户经理则不能分配
    let flag = filter.some(item => item.visitStatus != '未分配' && item.visitStatus != '未分配至客户经理' && item.visitStatus != '未走访');
    if (flag) {
      wx.showToast({
        icon: "none",
        title: "勾选企业中存在已走访数据",
        duration: 1500,
      });
      this.closeBtn();
      return
    }
    this.setData({
      showWin: true,
      showCheck: true,
      active: 'withdraw',
    });
  },
  selectChange(e) {

    this.setData({
      selectCheckbox: e.detail,
    });
    this.data.checkBtachList = [];
    this.data.selectCheckbox.forEach(item => {
      this.data.originList.forEach(ele => {
        if (item == ele.visitCorpId) {
          // 如果 checkBtachList 里面没有 ele.batchId 就push
          if (this.data.checkBtachList.indexOf(ele.batchId) == -1) {
            this.data.checkBtachList.push(ele.batchId)
          }
        }
      })
    });
  },
  changeOptype(e) {
    this.setData({
      optype: e.detail,
    });
  },
  changeRange(e) {
    this.setData({
      range: e.detail,
    });
  },

  withdrawOrDelete() {
    let para = {}
    para.opType = this.data.optype
    para.range = this.data.range
    para.ids = this.data.selectCheckbox
    para.batchIds = this.data.checkBtachList
    para.userId = wx.getStorageSync("userInfo").userId;
    para.token = wx.getStorageSync('token');
    // 校验para所有属性是否都有值 其中id为数组长度大于0
    if (para.ids.length == 0) {
      wx.showToast({
        icon: "none",
        title: "请选择企业",
      });
      return
    }
    if (Object.values(para).some(item => item == '')) {
      wx.showToast({
        icon: "none",
        title: "参数无效",
      });
      return
    }
    let tips = "";
    if (para.opType == 'withdraw') {
      // 分配前需要判断选中企业中是否有已分配的企业
      // let selectCheckbox = this.data.selectCheckbox;
      // let originList = this.data.originList;
      // let filter = originList.filter(item => selectCheckbox.includes(item.visitCorpId));
      // // 如果filter 中 visitStatus 有一项不等于 未分配或者不等于 未分配至客户经理则不能分配
      // let flag = filter.some(item => item.visitStatus != '未分配' && item.visitStatus != '未分配至客户经理');
      // if (flag) {
      //   wx.showToast({
      //     icon: "none",
      //     title: "选中企业中有已分配的企业，请先撤回选中企业",
      //   });
      //   this.setData({
      //     active: 'withdraw',
      //   })
      //   return
      // }




      if (para.range == 'single') {
        tips = "此操作将撤回所勾选走访企业下所有走访记录，是否撤回？"
      } else if (para.range == 'batch') {
        tips = "按批次撤回将撤回勾选所在批次下所有走访记录，是否撤回？"
      }
      wx.showModal({
        title: "提示",
        content: tips,
        success: (res) => {
          if (res.confirm) {
            console.log("用户点击确定");
            this.doConfirm(para)
          } else if (res.cancel) {
            console.log("用户点击取消");
          }
        },
      });

    } else if (para.opType == 'delete') {

      if (para.range == 'single') {
        tips = "此操作将删除所勾选走访企业及走企业下所有走访记录，是否删除？"
      } else if (para.range == 'batch') {
        tips = "按批次删除将删除勾选所在批次下所有走访企业及企业走访记录，是否删除？"
      }

      wx.showModal({
        title: "提示",
        content: tips,
        success: (res) => {
          if (res.confirm) {
            console.log("用户点击确定");
            this.doConfirm(para)
          } else if (res.cancel) {
            console.log("用户点击取消");
          }
        },
      });
    }

  },
  doConfirm(para) {
    this.setData({
      loadingIsshow: true,
      showCheck: false,
    })
    getApp().globalData.request(
      '/visit/withdrawOrDelete', {
        ...para
      },
      "POST"
    ).then(res => {
      this.setData({
        loadingIsshow: false,
      })
 
      if (res.code == 200) {
        this.setData({
          showWin: false,
          checkBtachList: [],
          selectCheckbox: [],
          range: '',
          optype: '',
        });
        wx.showToast({
          title: res.data,
          icon: 'none'
        })
        this.setData({
          originList: [],
          pageNum: 1
        });
        this.getList()
      } else {
        this.setData({
          showWin: false,
          showCheck: false,
          checkBtachList: [],
          selectCheckbox: [],
          range: '',
          optype: '',
        });
        wx.showToast({
          title: res.data,
          icon: 'none'
        })
      }
    });
  },
  getLeafNodeByname(text, node) {
    if (node.text === text) {
      return node;
    }
    if (node.children) {
      for (let i = 0; i < node.children.length; i++) {
        let leafNode = this.getLeafNodeByname(text, node.children[i]);
        if (leafNode) {
          return leafNode;
        }
      }
    }
  },

  firstSearch() {
    this.setData({
      originList: [],
      pageNum: 1
    });
    this.getList()
  },
  toprodetail(e) {
    wx.navigateTo({
      url: `/pages/mapDetail/mapDetail?corpKey=${e.detail.corpKey}&latitude=${e.detail.latitude}&longitude=${e.detail.longitude}&distance=${e.detail.distance}`,
    });
  },
  goOnChange(val) {
  
    this.data.searchParam = val.detail
  },
  goSearch() {
    this.data.pageNum = 1
    this.data.originList = []

    this.setData({
      originList: [],
     
    })
    this.getList()
  },
  getList() {

    // ================
    const params = {
      pageBO: {
        pageSize: this.data.pageSize,
        pageNum: this.data.pageNum,
      },
      searchParam: this.data.searchParam,
      fileName: this.data.fileName,
      bankId: this.data.bankId,
      agencyCode: this.data.agencyCode,
      // haveDevice:Number(this.data.haveDevice) 
    }
    console.log(params,'传递的参数')
    getApp().globalData.request(
      '/map/lookVisitCorpAround', {
        ...params
      },
      "POST"
    ).then(res => {
      res.data.list.forEach(element => {
        if(element.visitStatus=='未分配至具体支行'){
          element.visitStatus='未分配至客户经理'
        }
      });
      if (res.data.list.length > 0) {
        const list = this.data.originList.concat(res.data.list)
        // 处理进度

        this.setData({
          originList: list,
          total: res.data.total
        })
      }
    })
  },
  scrollBottom() {
    if (this.data.originList.length < this.data.total) {
      // this.onBottom();
      this.setData({
        pageNum: ++this.data.pageNum,
      });
      this.getList();
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(e) {
 
    if (e.bankId == '' || e.bankId == 'null' || e.bankId == null || e.bankId == undefined) {
      e.bankId = '暂未分配'
    }
    this.setData({
      bankId: e.bankId,
      bankName: e.bankName,
      fileName: e.fileName,
      agencyCode: e.agencyCode,
    })
    if(e.haveDevice){
      this.setData({
        haveDevice:Number(e.haveDevice) 
      })
    }else{
      this.setData({
        haveDevice:''
      })
    }
    
 
    this.getList()
    // this.getORG()
    this.getManages()
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    wx.setStorageSync('aShow', true)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})